<template>
  <div>
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    >
      <template #btns>
        <el-button v-if="meta.indexOf('MemberRechargeOrderListExcel') > -1" :loading="exportLoading" type="primary" @click="handleExport">{{ $t('message.daochu') }}</el-button>
      </template>
    </QueryForm>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-tableb"
    >
      <el-table-column
        align="center"
        :label="$t('message.ddh')"
        prop="orderId"
        min-width="220"
      />
      <el-table-column
        align="center"
        :label="$t('message.hyklx')"
        prop="cardType"
        min-width="120"
      />
      <el-table-column :label="$t('message.memberInfo')" min-width="250" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.nickName || '' }} {{ scope.row.phone || scope.row.memberCard ?'-':'' }}{{ scope.row.phone|| '' }}{{ scope.row.phone && scope.row.memberCard ?'-':'' }}{{ scope.row.memberCard || '' }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.ddlx')"
        prop="orderType"
        min-width="120"
      >
        <template v-slot="scope">
          <span v-if="scope.row.orderType === '01'">{{ $t('message.hycz') }}</span>
          <span v-if="scope.row.orderType === '05'">{{ $t('message.hykk') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.jyqd')" min-width="100">
        <template slot-scope="scope">
          <span>{{
            scope.row.channelTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('message.ddje')"
        prop="originalPrice"
        min-width="80"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ (scope.row.originalPrice + scope.row.giveMoney).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('message.czje')"
        prop="originalPrice"
        min-width="80"
        align="center"
      />
      <el-table-column :label="$t('message.zsje')" prop="giveMoney" width="80" align="center" />
      <el-table-column align="center" :label="$t('message.jyfs')" min-width="100" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ payMethod(scope.row.payMethod) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('message.jysj')"
        prop="createTime"
        min-width="160"
        align="center"
      />
      <el-table-column
        :label="$t('message.czrnc')"
        show-overflow-tooltip
        prop="creatorName"
        min-width="100"
        align="center"
      />
      <el-table-column
        :label="$t('message.status')"
        align="center"
        fixed="right"
        min-width="100"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.payStatusName || scope.row.statusName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('message.bz')"
        show-overflow-tooltip
        prop="note"
        min-width="120"
        align="center"
      />
      <el-table-column
        :label="$t('message.caozuo')"
        align="center"
        fixed="right"
        min-width="140"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="
                scope.row.payStatus === '0' &&
                  meta.indexOf('MemberContinueRecharge') > -1
              "
              type="text"
              @click="rowPay(scope.row)"
            >{{ $t('message.zf') }}</el-button>
            <el-button
              v-if="
                scope.row.payStatus === '0' &&
                  meta.indexOf('MemberCancelRecharge') > -1
              "
              type="text"
              @click="rowCancelPay(scope.row.orderId)"
            >{{ $t('message.qxzf') }}</el-button>
            <el-button
              v-if="
                scope.row.payStatus === '3' &&
                  meta.indexOf('RechargePrinterOrder') > -1
              "
              type="text"
              @click="handlePrint(scope.row, scope.row.orderType)"
            >{{ $t('message.dyxp') }}</el-button>
            <span
              v-if="scope.row.payStatus === '1' || scope.row.payStatus === '2'"
            >-</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="totalCount"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <orderDialog ref="child" @orderSuccess="getList()" />
    <RechargeTem v-if="isPrint" ref="RechargeTemRef" />
  </div>
</template>

<script>
import { getOrderTypeQuery, getChannelType, allConfigList, cardList, rechargeOrders, continueRecharge, cancelRecharge, printOrder, VipRechargeExport } from '@/api'
import { parseTime } from '@/utils'
import { queryFormConfig } from './config'
import dayjs from 'dayjs'
import QueryForm from '@/components/QueryForm'
import orderDialog from '@/components/order'
import RechargeTem from '@/components/printTem/recharge.vue'
export default {
  name: 'VipRechargeList',
  components: {
    QueryForm,
    RechargeTem,
    orderDialog
  },
  props: {
    meta: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      exportLoading: false,
      isPrint: false,
      queryFormConfig,
      pagination: {
        page: 1,
        rows: 10
      },
      totalCount: 0,
      allPayMethedList: [],
      list: [],
      listLoading: true,
      filters: {},
      orderStatusList: [
        { value: '0', label: this.$t('message.dzf') },
        { value: '1', label: this.$t('message.cswzf') },
        { value: '2', label: this.$t('message.qxzf') },
        { value: '3', label: this.$t('message.zfcg') }
      ]
    }
  },
  created() {
    this.listLoading = false
    this.initFilters()
    // this.queryFormConfig.formItems[6].options = this.orderStatusList
    this.getCardList()
    this.initData()
    this.getOrderStatusList()
    this.getChannel()
  },
  mounted() {
    this.$refs.table.doLayout()
  },
  methods: {
    getOrderStatusList() {
      getOrderTypeQuery({ param: {}}).then(res => {
        this.queryFormConfig.formItems[4].options = res.recordList || []
      })
    },
    getChannel() {
      getChannelType({ param: { code: 'CHANNEL_CARD' }}).then(res => {
        this.queryFormConfig.formItems[1].options = res.recordList.map(item => {
          return {
            label: item.name,
            value: item.value
          }
        })
      })
    },
    handleExport() {
      const { filters } = this
      const venueId = sessionStorage.getItem('venueId')
      if (filters.dates && filters.dates.length > 0) {
        filters.startDate = filters.dates[0]
        filters.endDate = filters.dates[1]
      }
      this.exportLoading = true
      VipRechargeExport({ param: { ...filters, venueId }}).then(res => {
        this.exportLoading = false
        if (res.errorCode !== '000000') return
        const elink = document.createElement('a')
        elink.style.display = 'none'
        elink.href = res.record.showUrl
        document.body.appendChild(elink)
        elink.click()
        document.body.removeChild(elink)
      }, () => {
        this.exportLoading = false
      })
    },
    initFilters() {
      let dates = []
      const start = new Date()
      const end = new Date()
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 29)
      dates = [dayjs(start).format('YYYY-MM-DD'), dayjs(end).format('YYYY-MM-DD')]
      // this.filters.dates = dates
      this.$set(this.filters, 'dates', dates)
    },
    rowPay(row) {
      continueRecharge({ param: { orderId: row.orderId }}).then(res => {
        if (res.errorCode !== '000000') return
        const obj = {
          allPrice: row.originalPrice || 0,
          giveMoney: row.giveMoney || 0,
          orderId: row.orderId,
          cardName: res.record.cardName,
          ...row
        }
        this.$refs.child.continuePay(obj, 'vipRecharge')
      })
    },
    getCardList() {
      cardList({
        pagination: {
          page: 1,
          rows: 1000
        },
        param: {
          type: '1'
        }
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            const arrb = res.recordList
            arrb.forEach(e => {
              e.label = e.cardName
              e.value = e.id
            })
            this.queryFormConfig.formItems[5].options = arrb
          }
        })
    },
    handlePrint(item, orderType) {
      this.isPrint = true
      printOrder({
        param: {
          contentMap: {},
          templateCode: orderType === '05' ? 'MECARDTPML' : 'MECHARGETPML',
          workId: item.orderId,
          venueId: sessionStorage.getItem('venueId')
        }
      }).then(res => {
        if (res.errorCode !== '000000') return
        if (res.record && res.record.isPrint === '1' && res.record.dataList && res.record.dataList.length > 0) {
          res.record.dataList.forEach(item => {
            this.$refs.RechargeTemRef.obj = { ...item }
            setTimeout(() => {
              this.$refs.RechargeTemRef.print()
            }, 300)
            setTimeout(() => {
              this.isPrint = false
            }, 500)
          })
        } else {
          this.isPrint = false
        }
      }).catch((err) => {
        this.isPrint = false
        console.log(err)
      })
    },
    rowCancelPay(orderId) {
      cancelRecharge({ param: { orderId }}).then(res => {
        if (res.errorCode !== '000000') return
        this.$message.success(this.$t('message.qxzfcg'))
        this.getList()
      })
    },
    payStatus(status) {
      const temp = this.orderStatusList.find(item => item.value === status)
      return temp ? temp.label : '-'
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    payMethod(status) {
      // 01-会员卡,02-现金,03-微信,04-支付宝,05微信扫码支付
      const temp = this.allPayMethedList.find(item => item.value === status)
      return temp ? temp.name : '-'
    },
    initData() {
      // 初始化请求
      allConfigList({ param: { type: '2', code: '1' }}).then(res => {
        if (res.errorCode !== '000000') return
        this.allPayMethedList = res.recordList
      }).catch(err => {
        console.log(err)
      })
      this.getList(1)
    },
    getList(page) {
      this.listLoading = true
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      if (filters.dates && filters.dates.length > 0) {
        filters.startDate = filters.dates[0]
        filters.endDate = filters.dates[1]
      } else {
        filters.startDate = null
        filters.endDate = null
      }
      rechargeOrders({ pagination, param: { venueId, ...filters }})
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.totalCount = res.totalCount
          this.list = res.recordList
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    clear() {
      this.filters = {}
      this.getList(1)
    }
  }
}
</script>

<style lang="scss" scoped>
.member_info {
  display: flex;
  flex-wrap: wrap;
  background: #f7f7f7;
  border-radius: 2px;
  padding: 16px;
  margin-top: 10px;
  .item {
    width: 50%;
    line-height: 28px;
    height: 28px;
  }
}
.vip-info {
  display: flex;
  justify-content: center;
  .name-phone {
    display: flex;
    flex: 1;
    flex-direction: column;
    justify-content: space-between;
    text-align: left;
    margin-left: 12px;
  }
}
</style>
